package com.bonana.core.utils;
import org.imgscalr.Scalr;
import com.bonana.utils.StringUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;

/**
 * 图片缩放
 * Created by Justin on 2014/8/29.
 */
public class ImageScaleUtil {

    public static String resizeImage(InputStream inputStream, String fileSuffix , int width, int height) throws IOException {
        String contentType = "image/jpeg";
        if (StringUtils.hasText(fileSuffix)) {
            if (fileSuffix.equalsIgnoreCase("jpg") || fileSuffix.equalsIgnoreCase("JPEG")) {
                contentType = "image/jpeg";
            } else if (fileSuffix.equalsIgnoreCase("png")) {
                contentType = "image/png";
            } else if (fileSuffix.equalsIgnoreCase("bmp")) {
                contentType = "image/x-bmp";
            } else if (fileSuffix.equalsIgnoreCase("GIF")) {
                contentType = "image/gif";
            }
        }
        BufferedImage image = readImage(inputStream, contentType);
        image = Scalr.resize(image, Scalr.Method.AUTOMATIC , Scalr.Mode.FIT_TO_WIDTH, width, height);
        FileInfo fileInfo =  OssUtils.putFile(bufferedImageToInputStream(image, fileSuffix), fileSuffix);
        if(fileInfo != null) {
            return fileInfo.getUrl();
        } else {
            return new String();
        }
    }

    public static InputStream bufferedImageToInputStream(BufferedImage bufferedImage, String suffix) {
        byte[] imageInByte = toByteArray(bufferedImage, suffix);
        return new ByteArrayInputStream(imageInByte);
    }

    public static byte[] toByteArray(BufferedImage bufferedImage, String suffix) {
        try {
            byte[] imageInByte;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, suffix, baos);
            baos.flush();
            imageInByte = baos.toByteArray();
            baos.close();

            return imageInByte;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    private static ImageInputStream createImageInputStream(InputStream is) throws IOException {
        return new MemoryCacheImageInputStream(is);
    }

    public static BufferedImage readImage(InputStream inputStream, String contentType) throws IOException {
        ImageInputStream imageInputStream = null;
        ImageReader imageReader = null;
        try {
            imageInputStream = createImageInputStream(inputStream);
            //MediaType mediaType = inputMessage.getHeaders().getContentType();
            //Iterator<ImageReader> imageReaders = ImageIO.getImageReadersBySuffix(suffix);

            Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType);
            if (imageReaders.hasNext()) {
                imageReader = imageReaders.next();
                ImageReadParam irp = imageReader.getDefaultReadParam();
                imageReader.setInput(imageInputStream, true);
                return imageReader.read(0, irp);
            } else {
                throw new HttpMessageNotReadableException("Could not find javax.imageio.ImageReader for  [" + contentType + "]");
            }
        } finally {
            if (imageReader != null) {
                imageReader.dispose();
            }
            if (imageInputStream != null) {
                try {
                    imageInputStream.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
    }

    protected static void save(BufferedImage image, String name) {
        try {
            ImageIO.write(image, getFileSuffix(name), new File(name));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static BufferedImage loadWebImage(String url) {
        InputStream is = null;
        HttpURLConnection huc = null;
        StringBuffer temp = null;
        try {
            huc = (HttpURLConnection) new URL(url).openConnection();
            huc.setRequestMethod("GET");
            huc.setUseCaches(true);
            huc.connect();

            is = huc.getInputStream();

            return readImage(is, huc.getHeaderField("Content-Type"));

//            reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
//
//            temp = new StringBuffer();
//            String str;
//            while ((str = reader.readLine()) != null) {
//                temp.append(str + "\r");
//            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                huc.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String getFileNameByUrl(String url) {
        int lastNo = url.lastIndexOf("/");
        if (url.substring(lastNo).lastIndexOf(".") == -1) {
            return url;
        } else {
            if ("".equals(url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")))) {
                getFileNameByUrl(url.substring(0, url.lastIndexOf("/")));
            } else {
                return url.substring(url.lastIndexOf("/") + 1);
            }
        }
        return url;
    }

    public static String getFileSuffix(String filename) {
        return filename.substring(filename.lastIndexOf(".") + 1, filename.length());
    }

    public static void main(String args[]) throws IOException {
        File file = new File("/Users/justin/Downloads/test/ff99fd8f49cc4950b7898f56cee14857.jpg");
        InputStream content = new FileInputStream(file);
        String contentType = "image/jpeg";
        String fileSuffix = "jpg";
        if (StringUtils.hasText(fileSuffix)) {
            if (fileSuffix.equalsIgnoreCase("jpg") || fileSuffix.equalsIgnoreCase("JPEG")) {
                contentType = "image/jpeg";
            } else if (fileSuffix.equalsIgnoreCase("png")) {
                contentType = "image/png";
            } else if (fileSuffix.equalsIgnoreCase("bmp")) {
                contentType = "image/x-bmp";
            } else if (fileSuffix.equalsIgnoreCase("GIF")) {
                contentType = "image/gif";
            }
        }
        BufferedImage image = ImageIO.read(content);
        image = Scalr.resize(image, Scalr.Method.AUTOMATIC , Scalr.Mode.AUTOMATIC, 180, 180);
        ImageScaleUtil.save(image, "/Users/justin/Downloads/test/saved." + fileSuffix);
    }

}
